package info.thereisonlywe.onenesspathfinder.ui;

import info.thereisonlywe.core.project.ProjectConstants;
import info.thereisonlywe.core.project.ProjectLocalization;
import info.thereisonlywe.core.toolkit.ArrayToolkit;
import info.thereisonlywe.core.toolkit.FileToolkit;
import info.thereisonlywe.core.toolkit.GUIToolkit;
import info.thereisonlywe.core.toolkit.StringToolkit;
import info.thereisonlywe.core.toolkit.ThreadToolkit;
import info.thereisonlywe.core.ui.swing.extensions.tooltip.MultiLineToolTip;
import info.thereisonlywe.quran.Quran;
import info.thereisonlywe.quran.QuranicVerse;
import info.thereisonlywe.salat.recitation.RecitationManager;
import info.thereisonlywe.salat.recitation.reciter.Reciter;
import info.thereisonlywe.salat.recitation.reciter.ReciterList;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JToggleButton;
import javax.swing.JToolTip;
import javax.swing.LayoutStyle.ComponentPlacement;

public class AudioPackageManagementDialog {

	private static boolean sigTerm = false;
	private static JDialog dialog;
	private static JLabel label_Reciter;
	private static JComboBox<String> comboBox_Reciter;
	private static JLabel label_Section;
	private static JComboBox<String> comboBox_Section;
	private static JCheckBox checkBox_FileIntegrityVerification;
	private static JToggleButton button_Download;
	private static JProgressBar progressBar_Download;

	/**
	 * @wbp.parser.entryPoint
	 */
	private static void init()
	{
		if (dialog != null) return;
		dialog = new JDialog();
		dialog.setIconImage(null);
		dialog.setTitle(ProjectLocalization.getString(
				ProjectConstants.ONENESS_PATHFINDER_PROJECT,
				"RecitationSettings"));
		dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		dialog.setResizable(false);
		dialog.setPreferredSize(new Dimension(330, 200));
		dialog.setSize(new Dimension(330, 200));
		dialog.setModal(true);
		dialog.getContentPane().setLayout(new BorderLayout());
		JPanel panel = new JPanel();
		dialog.getContentPane().add(panel, BorderLayout.CENTER);
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel
				.createParallelGroup(Alignment.TRAILING)
				.addGroup(
						gl_panel.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										gl_panel.createParallelGroup(
												Alignment.LEADING)
												.addComponent(
														getDownloadButton(),
														GroupLayout.DEFAULT_SIZE,
														304, Short.MAX_VALUE)
												.addGroup(
														gl_panel.createSequentialGroup()
																.addComponent(
																		getReciterLabel())
																.addPreferredGap(
																		ComponentPlacement.UNRELATED)
																.addComponent(
																		getReciterComboBox(),
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE))
												.addGroup(
														gl_panel.createSequentialGroup()
																.addComponent(
																		getSectionLabel())
																.addGap(10)
																.addComponent(
																		getSectionComboBox(),
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE))
												.addComponent(
														getFileIntegrityVerificationCheckBox())
												.addComponent(
														getProgressBar(),
														GroupLayout.DEFAULT_SIZE,
														304, Short.MAX_VALUE))
								.addContainerGap()));
		gl_panel.setVerticalGroup(gl_panel
				.createParallelGroup(Alignment.LEADING)
				.addGroup(
						gl_panel.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										gl_panel.createParallelGroup(
												Alignment.BASELINE)
												.addComponent(getReciterLabel())
												.addComponent(
														getReciterComboBox(),
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addGroup(
										gl_panel.createParallelGroup(
												Alignment.LEADING)
												.addGroup(
														gl_panel.createSequentialGroup()
																.addGap(4)
																.addComponent(
																		getSectionLabel()))
												.addComponent(
														getSectionComboBox(),
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(
										getFileIntegrityVerificationCheckBox())
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(getDownloadButton(),
										GroupLayout.DEFAULT_SIZE, 14,
										Short.MAX_VALUE)
								.addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(getProgressBar(),
										GroupLayout.DEFAULT_SIZE, 26,
										Short.MAX_VALUE).addGap(31)));
		panel.setLayout(gl_panel);
		dialog.addWindowListener(new WindowAdapter()
		{

			@Override
			public void windowClosing(WindowEvent e)
			{
				dialog.setVisible(false);
				UIDelegate.setOpenDialog(false);
			}
		});

		KeyboardFocusManager.getCurrentKeyboardFocusManager()
				.addKeyEventDispatcher(new KeyEventDispatcher()
				{
					@Override
					public boolean dispatchKeyEvent(KeyEvent e)
					{
						boolean keyHandled = false;
						if (e.getID() == KeyEvent.KEY_PRESSED
								&& dialog.isVisible())
						{
							if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
							{
								dialog.setVisible(false);
								UIDelegate.setOpenDialog(false);
								keyHandled = true;
							}
						}
						return keyHandled;
					}
				});

	}

	public synchronized static void showDialog()
	{
		init();
		dialog.setLocation(GUIToolkit.getCenteredWindowPosition(
				dialog.getWidth(), dialog.getHeight()));
		UIDelegate.setOpenDialog(true);
		dialog.setVisible(true);
	}

	protected static JLabel getReciterLabel()
	{
		if (label_Reciter == null)
		{
			label_Reciter = new JLabel(ProjectLocalization.getString(
					ProjectConstants.ONENESS_PATHFINDER_PROJECT,
					"SelectReciter"));
		}
		return label_Reciter;
	}

	protected static JComboBox<String> getReciterComboBox()
	{
		if (comboBox_Reciter == null)
		{
			comboBox_Reciter = new JComboBox<>();
			comboBox_Reciter.setModel(new DefaultComboBoxModel<String>(
					ReciterList.getReciterNames()));
		}
		return comboBox_Reciter;
	}

	protected static JLabel getSectionLabel()
	{
		if (label_Section == null)
		{
			label_Section = new JLabel(ProjectLocalization.getString(
					ProjectConstants.ONENESS_PATHFINDER_PROJECT,
					"SelectSection"));
		}
		return label_Section;
	}

	protected static JComboBox<String> getSectionComboBox()
	{
		if (comboBox_Section == null)
		{
			comboBox_Section = new JComboBox<>();
			comboBox_Section
					.setModel(new DefaultComboBoxModel<String>(
							ArrayToolkit.insertAtBeginning(
									Quran.getSectionNames(),
									ProjectLocalization
											.getString(
													ProjectConstants.ONENESS_PATHFINDER_PROJECT,
													"AllSections"))));
		}
		return comboBox_Section;
	}

	protected static JCheckBox getFileIntegrityVerificationCheckBox()
	{
		if (checkBox_FileIntegrityVerification == null)
		{
			checkBox_FileIntegrityVerification = new JCheckBox(
					ProjectLocalization.getString(
							ProjectConstants.ONENESS_PATHFINDER_PROJECT,
							"CheckFileIntegrity"));
		}
		return checkBox_FileIntegrityVerification;
	}

	protected static JToggleButton getDownloadButton()
	{
		if (button_Download == null)
		{
			button_Download = new JToggleButton(ProjectLocalization.getString(
					ProjectConstants.CORE_PROJECT, "Download"))
			{

				@Override
				public JToolTip createToolTip()
				{
					MultiLineToolTip tip = new MultiLineToolTip();
					tip.setComponent(this);
					return tip;
				}
			};
			button_Download.setToolTipText(StringToolkit.multiLine(
					ProjectLocalization.getString(
							ProjectConstants.ONENESS_PATHFINDER_PROJECT,
							"DownloadWindowClosed"),
					UIConstants.MAX_CHARS_PER_LINE));
			button_Download.addActionListener(new ActionListener()
			{

				@Override
				public void actionPerformed(ActionEvent e)
				{

					if (!button_Download.isSelected())
					{
						sigTerm = true;
						ThreadToolkit.sleep(3000);
						getSectionComboBox().setEnabled(true);
						getReciterComboBox().setEnabled(true);
						getProgressBar().setValue(0);
						getProgressBar().setVisible(false);
					}

					else
					{
						while (sigTerm)
						{
							ThreadToolkit.sleep(50);
						}
						getSectionComboBox().setEnabled(false);
						getReciterComboBox().setEnabled(false);
						getProgressBar().setVisible(true);

						Runnable r = new Runnable()
						{
							@Override
							public void run()
							{
								boolean error = false;
								getProgressBar().setValue(0);
								int section = getSectionComboBox()
										.getSelectedIndex();
								int sectionCount = section == 0 ? 114 : 1;
								section = (sectionCount == 114) ? 1 : (section);
								int versesInSection = Quran
										.getInSectionVerseCount(section);
								Reciter reciter = ReciterList
										.getReciterByName(((String) getReciterComboBox()
												.getSelectedItem()));
								getProgressBar()
										.setMaximum(
												(sectionCount == 114) ? Quran.VERSE_COUNT
														: (versesInSection));
								if (reciter.hasAudhubillah()
										&& !reciter.getFile(Quran.AUDHUBILLAH)
												.exists())
								{
									error = !RecitationManager
											.updateAudioFile(
													reciter,
													Quran.AUDHUBILLAH,
													getFileIntegrityVerificationCheckBox()
															.isSelected() ? FileToolkit.UPDATE_POLICY_IF_POSSIBLE
															: FileToolkit.UPDATE_POLICY_NEVER);
								}
								if (!error)
								{
									while (sectionCount > 0)
									{
										SECTION: for (int i = 1; i <= versesInSection; i++)
										{
											if (sigTerm)
											{
												sigTerm = false;
												return;
											}
											QuranicVerse verse = Quran
													.getVerse(section, i);
											if (!reciter.getFile(verse)
													.exists()
													|| getFileIntegrityVerificationCheckBox()
															.isSelected())
											{
												boolean b;
												if (verse.getIndex() == 0
														&& !reciter
																.hasBasmala()) b = true;
												else
												{
													b = RecitationManager
															.updateAudioFile(
																	reciter,
																	verse,
																	getFileIntegrityVerificationCheckBox()
																			.isSelected() ? FileToolkit.UPDATE_POLICY_IF_POSSIBLE
																			: FileToolkit.UPDATE_POLICY_NEVER);
												}
												if (!b)
												{
													UIDelegate
															.setOpenDialog(true);
													GUIToolkit.showErrorDialog(
															ProjectLocalization
																	.getString(
																			ProjectConstants.CORE_PROJECT,
																			"DownloadError"),
															StringToolkit.multiLine(
																	ProjectLocalization
																			.getString(
																					ProjectConstants.CORE_PROJECT,
																					"DownloadError.Body"),
																	UIConstants.MAX_CHARS_PER_LINE));
													UIDelegate
															.setOpenDialog(false);
													error = true;
													break SECTION;
												}
											}
											getProgressBar().setValue(
													progressBar_Download
															.getValue() + 1);
										}
										sectionCount--;
										if (sectionCount == 0) break;
										section++;
										versesInSection = Quran
												.getInSectionVerseCount(section);
									}
								}
								getDownloadButton().setSelected(false);
								getProgressBar().setValue(0);
								getProgressBar().setVisible(false);
								getSectionComboBox().setEnabled(true);
								getReciterComboBox().setEnabled(true);
								sigTerm = false;
								if (!error)
								{
									UIDelegate.setOpenDialog(true);
									GUIToolkit.showInformationDialog(
											ProjectLocalization
													.getString(
															ProjectConstants.CORE_PROJECT,
															"DownloadSuccessful"),
											StringToolkit.multiLine(
													ProjectLocalization
															.getString(
																	ProjectConstants.CORE_PROJECT,
																	"DownloadSuccessful.Body"),
													UIConstants.MAX_CHARS_PER_LINE));
									UIDelegate.setOpenDialog(false);
								}
							}
						};
						new Thread(r).start();
					}

				}
			});

		}
		return button_Download;
	}

	protected static JProgressBar getProgressBar()
	{
		if (progressBar_Download == null)
		{
			progressBar_Download = new JProgressBar();
			progressBar_Download.setStringPainted(true);
			progressBar_Download.setVisible(false);
		}
		return progressBar_Download;
	}
}
